package com.purchase.util;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author saw
 * @date 2021年11月12 14:25
 * @description 存储文件工具
 */
public class FileUtils {

    public static void fileWrite(String path, String content){
        try(RandomAccessFile raf = new RandomAccessFile(path,"rw");
            FileChannel writeFileChannel = raf.getChannel()){

            ByteBuffer buf = ByteBuffer.allocate(content.getBytes(StandardCharsets.UTF_8).length);
            buf.clear();
            buf.put(content.getBytes(StandardCharsets.UTF_8));
            // 转为读模式
            buf.flip();
            writeFileChannel.write(buf);
            //流可以省略不关闭了
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void fileWrite(String path, byte[] bytes){
        try(RandomAccessFile raf = new RandomAccessFile(path,"rw");
            FileChannel writeFileChannel = raf.getChannel()){

            ByteBuffer buf = ByteBuffer.allocate(bytes.length);
            buf.clear();
            buf.put(bytes);
            // 转为读模式
            buf.flip();
            writeFileChannel.write(buf);
            //流可以省略不关闭了
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String fileRead(String path){
        StringBuilder strBuffer = new StringBuilder();
        try(RandomAccessFile raf = new RandomAccessFile(path,"rw");
            FileChannel readFileChannel = raf.getChannel()){

            ByteBuffer buf = ByteBuffer.allocate(1024);

            while (readFileChannel.read(buf) != -1){

                buf.flip();
                //循环写
                strBuffer.append(StandardCharsets.UTF_8.decode(buf));
                buf.clear();
            }
            //流可以省略不关闭了
        }catch (Exception e){
            e.printStackTrace();
        }
        return strBuffer.toString();
    }
}
